package com.atguigu.tingshu.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * feign接口的拦截器
 */
@Component
public class GuiguFeignInterceptor implements RequestInterceptor {

    /**
     * feign调用的http请求发起前触发
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取原request对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //一定要判断!!
        if(requestAttributes != null){
            //获取原request对象
            HttpServletRequest request = requestAttributes.getRequest();
            //获取原请求request的请求头中全部的参数
            Enumeration<String> headerNames = request.getHeaderNames();
            //迭代存储
            while (headerNames.hasMoreElements()){
                //获取元素
                String name = headerNames.nextElement();
                //获取value
                String value = request.getHeader(name);
                // 将请求长度校验移除
                if (name.equals("content-length")){
                    continue;
                }
                //存储
                requestTemplate.header(name, value);
            }
        }
    }
}